package com.lvmama.rhino.collector.utils

import java.io.{ByteArrayInputStream, ByteArrayOutputStream, IOException}
import java.util.zip.{GZIPInputStream, GZIPOutputStream}


import org.apache.commons.codec.binary.Base64

/**
  * Created by yuanxiaofeng on 2016/3/11.
  */
object GZipUtils {
  /**
    * 输出字符集
    */
  private val OUTPUT_CHARSET: String = "UTF-8"

  /**
    * 字符串的压缩
    *
    * @param str 待压缩的字符串
    * @return 返回压缩后的字符串
    * @throws IOException
    */
  @throws(classOf[IOException])
  def compress(str: String): String = {
    require(null != str && str.length > 0)
    val out: ByteArrayOutputStream = new ByteArrayOutputStream
    val gzip: GZIPOutputStream = new GZIPOutputStream(out)
    gzip.write(str.getBytes)
    gzip.close
//    out.toString(INPUT_CHARSET)
    Base64.encodeBase64String(out.toByteArray)

  }

  /**
    * 字符串的解压
    *
    * @param str 对字符串解压
    * @return 返回解压缩后的字符串
    * @throws IOException
    */
  @throws(classOf[IOException])
  def unCompress(str: String): String = {
    require(null != str && str.length > 0)
    val out: ByteArrayOutputStream = new ByteArrayOutputStream
    val in: ByteArrayInputStream = new ByteArrayInputStream(Base64.decodeBase64(str))
    val gzip: GZIPInputStream = new GZIPInputStream(in)
    val buffer: Array[Byte] = new Array[Byte](1024)
    var n: Int = 0
    while ((({
      n = gzip.read(buffer); n
    })) >= 0) {
      out.write(buffer, 0, n)
    }
    out.toString(OUTPUT_CHARSET)
  }
}
